<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item v-breadcrumb-certify></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content plan_temp_list">
      <el-row class="switchBtn">
        <el-col :span="16">
          <e-heading style="margin-top:0;margin-bottom:0" :grade="'1'">{{$t('train["训练计划（每课时）"]')}}</e-heading>
          <span class="form-help">{{$t('train["训练计划为每个课时的详细教学过程，由课时主题和训练方式组成。"]')}}</span>
        </el-col>
        <el-col :span="8" class="tr">
          <switch-i18n-btn />
        </el-col>
      </el-row>
      <el-form v-bind="getFormProps()" :inline="true">
        <el-form-item label="">
          <el-input size="small" v-model.trim="query.topic" :placeholder="$t(`train['请输入课时主题名称']`)"></el-input>
        </el-form-item>
        <el-button size="small" type="primary-plain" native-type="submit">{{$t("搜索")}}</el-button>
      </el-form>
      <el-row class="switchBtn">
        <el-col :span="16">
          <e-heading style="margin-top:0;" :grade="'1'">{{$t('train["训练计划模板列表"]')}}</e-heading>
        </el-col>
        <el-col :span="8" class="tr">
          <el-button size="small" @click="handleAddPlanTemp"  type="primary">
            {{$t('train["新增计划模板"]')}}
          </el-button>
        </el-col>
      </el-row>
      <el-tabs v-model="query.authStatus" @tab-click="handleTabChange">
        <el-tab-pane :label="$t(`train['已通过']`)" name="2"></el-tab-pane>
        <el-tab-pane :label="$t(`train['待审核']`)" name="0"></el-tab-pane>
        <el-tab-pane :label="$t(`train['未通过']`)" name="1"></el-tab-pane>
      </el-tabs>
      <div v-if="plan_list.list && plan_list.list.length > 0">
        <div v-for="(item, index) in plan_list.list" :key="index" class="list-dis">
          <el-table 
            v-bind="getTableProps()"
              border
            :data="[item]" 
            tooltip-effect="dark">
            <el-table-column 
              prop="topic"
              :label="$t(`train['课时主题']`)" 
              width="320"
              :show-overflow-tooltip="true"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.topic }}
              </template>
            </el-table-column>
            <el-table-column 
              prop="userName"
              :label="$t(`train['编辑人']`)" 
              width="140"
              :show-overflow-tooltip="true"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.userName }}
              </template>
            </el-table-column>
            <el-table-column 
              prop="createTime"
              :label="$t(`train['提交时间']`)" 
              width="130"
              align="center">
              <template slot-scope="scope">
                {{new Date(scope.row.createTime).format('yyyy-MM-dd hh:mm')}}
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('操作')"
              align="center">
              <template slot-scope="scope">
                <!-- 审核通过 -->
                <div v-if="query.authStatus == 2"> 
                  <el-button type="link" @click.prevent="handleClone(scope.$index, scope.row, $event)" :loading="loading" v-if="roleType != 99">{{$t('train["复制模板"]')}}</el-button>
                  <el-button type="link" @click="handleDetail(scope.$index, scope.row, 2)">{{$t('详情')}}</el-button>
                  <el-button type="link" @click="handleEdit(scope.$index, scope.row)" v-if="roleType != 99">{{$t('编辑')}}</el-button>
                  <el-button type="link" @click="handleDelete(scope.$index, scope.row, $event)" :loading="loading" v-if="roleType != 99">{{$t('删除')}}</el-button>
                  <el-button type="link" @click="handleExportTemp(scope.$index, scope.row, $event)" :loading="loading">{{$t('导出')}}</el-button>
                </div>
                <!-- 待审核 -->
                <div v-else-if="query.authStatus == 0">
                  <el-button type="link" @click="handleDetail(scope.$index, scope.row, 0)">{{$t('详情')}}</el-button>
                  <el-button type="link" @click="handlePass(scope.$index, scope.row, $event)" :loading="loading" v-if="roleType != 99">{{$t('通过')}}</el-button>
                  <el-button type="link" @click="handleDeny(scope.$index, scope.row, $event)" :loading="loading" v-if="roleType != 99">{{$t('拒绝')}}</el-button>
                </div>
                <!-- 未通过 -->
                <div v-else>
                  <el-button type="link" @click="handleDetail(scope.$index, scope.row, 1)">{{$t('详情')}}</el-button>
                  <el-button type="link" @click="handleEdit(scope.$index, scope.row)">{{$t('编辑')}}</el-button>
                  <el-button type="link" @click="handleDelete(scope.$index, scope.row, $event)" :loading="loading">{{$t('删除')}}</el-button>
                  <el-button type="link" @click="handleAgainsubmit(scope.$index, scope.row, $event)" :loading="loading">{{$t('再次提交')}}</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div> 
        <el-pagination
          v-bind="getPaginationProps(plan_list)"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          >
        </el-pagination>
      </div>
      <!--无数据提示-->
      <e-placeholder :text="$t('暂无数据')" src="/static/images/training/no_course.png" v-else></e-placeholder>
      <!-- 主题名称过长弹框修改 -->
      <el-dialog :title="$t('提示')" :visible.sync="dialogVisible" @close="dialogVisible = false">
        <div class="dialog_remind">{{$t('train["复制模板的名称太长，请修改！"]')}}</div>
        <el-form ref="form" v-bind="getFormProps({labelWidth: '142px'})" :model="form" @submit.native.prevent>
          <el-form-item :label="$t(`train['复制的课时主题']`) + $t('：')" prop="topic" :rules="[
              {required: true, message: $t(`train['请输入主题名称']`)},
              Object.assign({trigger: 'blur', validator: validator.rule.checkTopic.validator.bind(this)})
            ]">
            <el-input v-model="form.topic" :maxlength="25" number-word style="width: 90%;" v-focus></el-input>
          </el-form-item>
          <el-form-item label-width="10px" class="button-box">
            <el-button type="primary" @click="handleDialog(parmasId)">{{$t('确定')}}</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { pagingList } from 'utils/mixins'
import api from 'api/trainingProgram'
import {mapGetters} from 'vuex'
import { TYPE_ENUM } from './constant'
import {downloadFile} from 'utils'
import validator from 'utils/validator'

export default {
  mixins: [pagingList],
  computed: {
    ...mapGetters({
      plan_list: 'plan_list'
    })
  },
  data () {
    return {
      validator,
      loading: false,
      query: this.getQuery({authStatus: this.$route.query.authStatus || '2'}),
      dialogVisible: false,
      form: {
        topic: ''
      },
      parmasId: '', // 复制训练计划模板id
      roleType: ''
    }
  },
  created () {
    this.roleType = localStorage.getItem('role_type') - 0
  },
  methods: {
    fetch (query) {
      this.$store.dispatch('plan_list', query)
    },
    handleAddPlanTemp () {
      this.$router.push({name: 'planTemplate', query: {type: TYPE_ENUM.ADD}})
    },
    handleTabChange (tab, event) {
      this.fetch(this.query)
    },
    handleExportTemp (index, row) { // 导出
      let fileName = this.$t(`train['训练计划']`) + '《' + row.topic + '》.docx'
      let url = '/api/train/plan/trainingPlanExport?trainPlanId=' + row.id
      downloadFile(url, fileName)
    },
    handleClone (index, row, event) { // 复制
      if (row.topic && row.topic.length > 22) {
        this.dialogVisible = true
        this.parmasId = row.id
        console.log(this.parmasId)
      } else {
        api.clonePlanTemp({id: row.id, topic: row.topic + '的副本'}, {context: event.target, successMsg: this.$t(`train['复制成功']`)}).then(() => {
          this.fetch(this.query)
        })
      }
    },
    handleDialog (parmasId) { // 长度超过25字时复制弹框
      this.$refs['form'].validate((valid) => {
        if (valid) {
          api.clonePlanTemp({id: parmasId, topic: this.form.topic}, {context: this, successMsg: this.$t(`train['复制成功']`)}).then(() => {
            this.form.topic = ''
            this.dialogVisible = false
            this.fetch(this.query)
          })
        }
      })
    },
    handleEdit (index, row) { // 编辑
      this.$router.push({name: 'planTemplate', query: {trainPlanId: row.id, type: TYPE_ENUM.EDIT}})
    },
    handleDelete (index, row, event) { // 删除
      const h = this.$createElement
      api.getDeleteBef({trainPlanId: row.id}, {context: event.target, errorMsg: 'none'}).then(res => {
        this.$msgbox({
          title: this.$t('温馨提示'),
          message: h('div', null, [
            h('div', null, this.$t(`train['确定删除该模板吗？']`)),
            h('div', { style: 'margin-top: 10px' }, this.$t(`train['删除后将不可恢复']`))
          ]),
          cancelButtonText: this.$t('取消'),
          confirmButtonText: this.$t('确定'),
          showCancelButton: true,
          type: 'warning'
        }).then(res => {
          api.deletePlan({id: row.id}, {context: event.target, successMsg: this.$t('删除成功')}).then(res => {
            this.fetch(this.query)
          })
        }).catch(() => {})
      }).catch(err => {
        this.$confirm(err.msg, this.$t('温馨提示'), {
          confirmButtonText: this.$t(`train['我知道了']`),
          showCancelButton: false,
          type: 'warning'
        }).catch(() => {})
      })
    },
    handleDetail (index, row, status) { // 详情
      this.$router.push({path: '/training/trainingprogram/plan/detail', query: {id: row.id, status: status}})
    },
    handlePass (index, row, event) { // 通过
      api.checkPlanTemp({id: row.id, auditStatus: 2}, {context: event.target, successMsg: this.$t(`train['审核通过']`)}).then(() => {
        this.fetch(this.query)
      })
    },
    handleDeny (index, row, event) { // 拒绝
      api.checkPlanTemp({id: row.id, auditStatus: 1}, {context: event.target, successMsg: this.$t(`train['审核未通过']`)}).then(() => {
        this.fetch(this.query)
      })
    },
    handleAgainsubmit (index, row, event) { // 再次提交
      api.checkPlanTemp({id: row.id, auditStatus: this.roleType !== 99 ? 2 : 0, checkAgain: new Date().getTime()}, {context: event.target, successMsg: this.$t(`train['再次提交成功']`)}).then(() => {
        this.fetch(this.query)
      })
    }
  }
}
</script>

<style lang="scss">
  .plan_temp_list {
    .el-form {
      padding-top: 30px;
    }
    .fixed-explain {
      position: relative;
      .form-help {
        position: absolute;
        top: 50px;
        left: 0px;
      }
    }
    .list-dis {
      width:100%;
      padding-bottom: 30px;
    }
    .el-table {
      border: 1px solid #f2f2f2;
    }
  }
  .dialog_remind {
    margin: 30px 0
  }
</style>
